package fun.flyee.android.pengshan.acts.helper;

import android.app.Service;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Handler;
import android.os.IBinder;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.demo.MonitorActivity;
import com.hcvsa.HCVSAService;
import com.hcvsa.MyHCVSA;
import com.hcvsa.OnCMSLoginResult;
import com.hcvsa.OnCMSLoginStatus;
import com.hcvsa.ReturnMeetingRoomInfo;
import com.hcvsa.UserCallInvite;
import com.hcvsa.UserInviteMyJoinMeeting;
import com.squareup.otto.Subscribe;
import com.until.BusProvider;

import org.greenrobot.eventbus.EventBus;

import java.util.HashMap;
import java.util.Map;

import fun.flyee.android.pengshan.Constant;
import fun.flyee.android.pengshan.Storage;
import fun.flyee.android.pengshan.acts.CallActivity;
import fun.flyee.android.pengshan.acts.Router;
import fun.flyee.android.pengshan.api.ApiClient;
import fun.flyee.android.pengshan.events.GetConferenceEvent;
import fun.flyee.android.pengshan.events.StartAudioRecordEvent;
import fun.flyee.android.pengshan.events.StopAudioRecordEvent;
import fun.flyee.android.pengshan.events.UnauthEvent;
import fun.flyee.android.pengshan.models.UserInfo;
import fun.flyee.android.pengshan.services.AppService;
import fun.flyee.android.pengshan.utils.Logger;
import fun.flyee.android.pengshan.utils.MD5;
import fun.flyee.android.pengshan.utils.Systems;
import fun.flyee.android.pengshan.widgets.Tips;
import fun.flyee.pengshan.social.BuildConfig;
import hcvs.audio.AudioPlay;
import hcvs.hcvca.bean.MeetingRoom;
import hcvs.hcvsa.SystemEvent;

public class ServiceHelper {

    private static ServiceHelper instance;

    private Context mContext;
    private boolean isServiceInit = false;
    private Handler mHandler;
    private HCVSAService.ServiceBinder videoServiceBinder;

    private ServiceConnection conn = new ServiceConnection() {
        @Override
        public void onServiceDisconnected(ComponentName arg0) {
            isServiceInit = false;
            UserInfo user = Storage.getUser();
            if (user != null) {
                ApiClient.log(user.id, "serviceHelper", "onServiceDisconnected");
            } else {
                mHandler.post(() -> EventBus.getDefault().post(new UnauthEvent()));
            }
        }

        @Override
        public void onServiceConnected(ComponentName name, IBinder serviceBinder) {
            isServiceInit = true;
            if (!isArmeabi()) return;
            UserInfo user = Storage.getUser();
            if (user != null) {
                ApiClient.log(user.id, "serviceHelper", "onServiceConnected");
            } else {
                mHandler.post(() -> EventBus.getDefault().post(new UnauthEvent()));
            }
            videoServiceBinder = (HCVSAService.ServiceBinder) serviceBinder;
            ApiClient.getDictByCode("appdlhcmm", (ret) -> {
                if (ret.code == 200) {
                    JSONObject json = JSONObject.parseObject(ret.data.toString());
                    loginVideo(json.getString("dictValue"));
                }
            });
        }
    };

    private ServiceHelper(Context ctx) {
        this.mContext = ctx;
        this.mHandler = new Handler();
        BusProvider.getInstance().register(this);
        AudioPlay.setM_audio_play_mode(AudioPlay.CONFIG_AUDIO_PLAY_MODE_AUDIO_TRACK);
        serviceInit();
        instance = this;
    }

    public static ServiceHelper getInstance(Context context) {
        if (instance == null) {
            instance = new ServiceHelper(context);
        } else {
            if (instance.videoServiceBinder != null) {
                instance.videoServiceBinder.checkTrace();
            }
        }
        return instance;
    }

    private void serviceInit() {
        Intent serviceIntent = new Intent(mContext, AppService.class);
        mContext.bindService(serviceIntent, conn, Service.BIND_AUTO_CREATE);
    }

    public void destroy() {
        try {
            BusProvider.getInstance().unregister(this);
            mContext.unbindService(conn);
            this.mContext = null;
            instance = null;
        } catch (Exception e) {
            Logger.e("nothing", e);
        }
    }

    private void loginVideo(String pwd) {
        try {
            UserInfo user = Storage.getUser();
            if (user == null) return;
            if (BuildConfig.DEBUG) return;
//            String pwd = MD5.md5("zxpo901@#+").substring(8, 24);
//            String pwd = MD5.md5("123456").substring(8, 24);
//            String pwd = "d3a8a13ff5ebb2e1";
            Logger.i("video", user.userName + " / " + pwd);
            MyHCVSA.getInstance().OnCMSCreate(Constant.videoUrl(), Constant.videoPort(),
                    user.userName,
                    pwd.toLowerCase());
            Logger.i("call rtc login");
        } catch (Exception e) {
            Logger.e("login video failed", e);
        }
    }

    @Subscribe
    public void startAudioRecord(StartAudioRecordEvent ev) {
        videoServiceBinder.audioInit(ev.channel);
    }

    @Subscribe
    public void stopAudioRecord(StopAudioRecordEvent ev) {
        videoServiceBinder.audioUnit();
    }

    @Subscribe
    public void OnCMSLoginResult(OnCMSLoginResult data) {
        if (data.getLoginResult() == SystemEvent.HCVS_LOGIN_RESULT_OK) {
            Logger.i("video登录结果:登录成功.");
            // 当登录成功并且Activity初始化完成后调用此函数，通知服务端已经初始化完成，这时服务端就会发送在线用户信息等数据
            if (!isArmeabi()) return;
            MyHCVSA.getInstance().CMSConnectActivity();
            ApiClient.get("/back-stage/app/setSessionId/" + MyHCVSA.getInstance().getUserSessionMoudle().GetMySessionid(), null, (resp) -> {
                if (BuildConfig.DEBUG && resp != null) {
                    Logger.i("setSessionId" + resp.code + " : " + resp.msg);
                }
            });
        } else if (data.getLoginResult() == SystemEvent.HCVS_LOGIN_RESULT_LOGIN_INIT_OVER) {
            Logger.i("video登录结果:登录成功(初始化完成).");
        } else {
            Logger.e("登录结果:登录失败,错误码:" + data.getLoginResult() + "!");
        }
    }

    @Subscribe
    public void ReturnMeetingRoomInfo(ReturnMeetingRoomInfo data) {
        MeetingRoom meetingRoom = data.getMeetingRoom();
        Map<String, String> meetingMap = new HashMap<String, String>();
        meetingMap.put("meetingName", meetingRoom.getRoomName());
        meetingMap.put("meetingHost", "主持人:" + meetingRoom.getHostName());
        meetingMap.put("meetingUserCount", meetingRoom.getOnlineNumber() + "人在线");
        meetingMap.put("meetingRoomId", Integer.toString(meetingRoom.getId()));
        meetingMap.put("isPassword", Integer.toString(meetingRoom.getIsPassword()));
        Logger.i("meeting", "返回会议室列表name=" + meetingRoom.getRoomName() + ", id=" + meetingRoom.getId());
        mHandler.post(() -> EventBus.getDefault().post(new GetConferenceEvent(JSONObject.toJSONString(meetingRoom))));
    }

    @Subscribe
    public void UserCallInvite(UserCallInvite data) {
        int sessionid = data.getSessionid();
        if (sessionid == 0) return;
        Router.popupDialog(mContext, 1, data.getSessionid(), data.getCalltype(), data.getName());
    }

    @Subscribe
    public void UserInviteMyJoinMeeting(UserInviteMyJoinMeeting data) {
        Logger.i("UserInviteMyJoinMeeting");
        Router.popupDialog(mContext, 2, data.getRoomid(), 0, data.getRoom_name());
    }

    public void playMonitor(String channel) {
        if (!isServiceInit) return;
        try {
            Intent in = new Intent(mContext, MonitorActivity.class);
            in.putExtra("channelid", Integer.parseInt(channel));
            mContext.startActivity(in);
        } catch (Exception e) {
            Logger.e("VideoHelper", e);
        }
    }

    public void getConferenceList() {
        if (!isArmeabi()) return;
        MyHCVSA.getInstance().getMeetingMoudle().RequestMeetingList(0);
    }

    private boolean isArmeabi() {
        return Systems.getCPUABI().contains("arm");
    }

}
